#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
环境验证脚本 - 验证VSCode和LangGraph环境配置
"""
import os
import sys
import io

# 设置UTF-8输出环境
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

def verify_project_structure():
    """验证项目结构"""
    print("📁 验证项目结构...")
    
    required_dirs = [
        'agents', 'simulator', 'llm', 'config', 'tests', 
        'logs', 'data', '.vscode'
    ]
    
    required_files = [
        'main.py', 'demo.py', 'run_tests.py', 'README.md',
        'requirements.txt', 'environment.yml', '.env',
        '.vscode/settings.json', '.vscode/launch.json'
    ]
    
    all_good = True
    
    for directory in required_dirs:
        if os.path.exists(directory):
            print(f"  ✅ 目录 {directory}/")
        else:
            print(f"  ❌ 缺少目录 {directory}/")
            all_good = False
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"  ✅ 文件 {file_path}")
        else:
            print(f"  ❌ 缺少文件 {file_path}")
            all_good = False
    
    return all_good

def verify_python_modules():
    """验证Python模块"""
    print("\n🐍 验证Python模块...")
    
    core_modules = [
        ('numpy', '数值计算库'),
        ('simulator.sim_engine', '雷达仿真引擎'),
        ('simulator.sim_controller', '仿真控制器')
    ]
    
    optional_modules = [
        ('langchain', 'LangChain框架'),
        ('langgraph', 'LangGraph框架'),  
        ('dashscope', 'DashScope API')
    ]
    
    success_count = 0
    
    for module, desc in core_modules:
        try:
            __import__(module)
            print(f"  ✅ {desc} ({module})")
            success_count += 1
        except ImportError as e:
            print(f"  ❌ {desc} ({module}): {e}")
    
    for module, desc in optional_modules:
        try:
            __import__(module)
            print(f"  ✅ {desc} ({module}) [可选]")
        except ImportError:
            print(f"  ⚠️ {desc} ({module}) [可选，智能体功能需要]")
    
    return success_count == len(core_modules)

def verify_vscode_config():
    """验证VSCode配置"""
    print("\n💻 验证VSCode配置...")
    
    vscode_configs = {
        '.vscode/settings.json': 'VSCode设置',
        '.vscode/launch.json': '调试配置',
        'environment.yml': 'Conda环境配置',
        'requirements.txt': 'Python依赖',
        '.env': '环境变量'
    }
    
    all_configs_exist = True
    
    for config_file, desc in vscode_configs.items():
        if os.path.exists(config_file):
            print(f"  ✅ {desc} ({config_file})")
        else:
            print(f"  ❌ 缺少{desc} ({config_file})")
            all_configs_exist = False
    
    return all_configs_exist

def run_quick_test():
    """运行快速功能测试"""
    print("\n🧪 运行快速功能测试...")

    try:
        from simulator.sim_controller import SimController

        # 创建临时控制器
        controller = SimController('logs/verify_test.log')
        
        # 测试基本功能
        response = controller.radar_control("状态查询")
        if "雷达仿真系统状态报告" in response:
            print("  ✅ 状态查询功能正常")
        else:
            print("  ❌ 状态查询功能异常")
            return False
        
        # 测试目标添加
        response = controller.radar_control("添加目标,测试,10,15,3,100,80,0,1.5")
        if "SUCCESS" in response or "added successfully" in response:
            print("  ✅ 目标管理功能正常")
        else:
            print("  ❌ 目标管理功能异常")
            return False

        # 测试仿真控制
        response = controller.radar_control("开始仿真")
        if "SUCCESS" in response or "started successfully" in response:
            print("  ✅ 仿真控制功能正常")
        else:
            print("  ❌ 仿真控制功能异常")
            return False
        
        print("  ✅ 核心功能测试通过")
        return True
        
    except Exception as e:
        print(f"  ❌ 功能测试失败: {e}")
        return False

def print_usage_instructions():
    """打印使用说明"""
    print("\n📖 VSCode使用指南:")
    print("=" * 50)
    print("1. 环境配置:")
    print("   - 确保安装Anaconda/Miniconda")
    print("   - 运行: conda env create -f environment.yml")
    print("   - 激活: conda activate LangGraph")
    print("   - 安装依赖: pip install -r requirements.txt")
    
    print("\n2. VSCode配置:")
    print("   - 打开VSCode")
    print("   - 文件 -> 打开文件夹 -> 选择RadarSimulationAgent目录")
    print("   - Ctrl+Shift+P -> Python: Select Interpreter")
    print("   - 选择LangGraph环境的Python解释器")
    
    print("\n3. 运行程序:")
    print("   - 按F5启动调试")
    print("   - 或在终端运行: python main.py")
    print("   - 演示程序: python demo.py")
    print("   - 运行测试: python run_tests.py")
    
    print("\n4. 调试功能:")
    print("   - 在代码行左侧点击设置断点")
    print("   - 按F5启动调试模式")
    print("   - 使用调试面板查看变量和调用栈")

def main():
    """主函数"""
    print("🎯 雷达仿真智能体VSCode环境验证")
    print("=" * 50)
    
    # 验证项目结构
    structure_ok = verify_project_structure()
    
    # 验证Python模块
    modules_ok = verify_python_modules()
    
    # 验证VSCode配置
    vscode_ok = verify_vscode_config()
    
    # 运行快速测试
    test_ok = run_quick_test()
    
    # 总结验证结果
    print("\n📊 验证结果总结:")
    print("=" * 30)
    print(f"项目结构: {'✅ 正常' if structure_ok else '❌ 异常'}")
    print(f"Python模块: {'✅ 正常' if modules_ok else '❌ 异常'}")
    print(f"VSCode配置: {'✅ 正常' if vscode_ok else '❌ 异常'}")
    print(f"功能测试: {'✅ 通过' if test_ok else '❌ 失败'}")
    
    if all([structure_ok, modules_ok, vscode_ok, test_ok]):
        print("\n🎉 环境验证完成！VSCode环境配置正确！")
    else:
        print("\n⚠️ 部分验证失败，请检查配置")
    
    # 显示使用说明
    print_usage_instructions()

if __name__ == "__main__":
    main()